/**
 * 
 */
package com.zito.manager;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.downlove.common.RequestContext;
import com.downlove.database.QueryHelper;
import com.downlove.database.SequenceManager;
import com.zito.ErrMsgException;
import com.zito.bean.Article;
import com.zito.bean.Articlefiles;
import com.zito.bean.Articlephotos;
import com.zito.bean.Columnz;
import com.zito.db.ColumnsDB;

/**
 * @author YunHai.Jiang
 * 
 */
public class ColumnManager {
	Columnz column = new Columnz();
	ColumnsDB dao = new ColumnsDB();

	private final Logger logger = LoggerFactory
			.getLogger(ColumnManager.class);
	
	/**
	 * 获取所有栏目专题分类
	 * @return
	 * @throws ErrMsgException
	 */
	public List<Columnz> getListAll() throws  ErrMsgException{
		String sql = "SELECT * FROM columnz WHERE (`TYPE`=0 AND `function` IN (0)) OR `TYPE`=1 ORDER BY ORDERS";
		List<Columnz> list = QueryHelper.query(Columnz.class, sql);
	    return list;
	}
	
	/**
	 * 获取专题列表
	 * @return
	 * @throws ErrMsgException
	 */
	public List<Columnz> getSpecialList() throws  ErrMsgException{
		String sql = "SELECT * FROM columnz WHERE `TYPE`=1 ORDER BY ORDERS";
		List<Columnz> list = QueryHelper.query(Columnz.class, sql);
	    return list;
	}
	
	/**
	 * 获取 功能为 图文类 栏目
	 * @return
	 * @throws ErrMsgException
	 */
	public List<Columnz> getColumnzList() throws  ErrMsgException{
		String sql = "SELECT * FROM columnz WHERE `TYPE`=0 AND `function` IN (0) ORDER BY ORDERS";
		List<Columnz> list = QueryHelper.query(Columnz.class, sql);
	    return list;
	}

	@SuppressWarnings("unchecked")
	public List<Columnz> getParentListByColumnzID(long columnzid) {
		Columnz columnz = column.Get(columnzid);
		if (columnz == null)
			return null;
		String[] tmpString = columnz.getParentlist().split(",");
		if (tmpString.length == 0)
			return null;
		List<Long> tmpLong = new ArrayList<Long>();
		for (String tmp : tmpString) {
			Long tmpl = Long.valueOf(tmp);
			if (tmpl != -1)
				tmpLong.add(Long.valueOf(tmp));
		}
		tmpLong.add(columnzid);
		return column.LoadList(tmpLong);
	}
	
	public Columnz addColumns() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		column = null;
		column = rc.form(Columnz.class);
		String error = column.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		if (column.getParentid() != -1) {
			Columnz parent = new Columnz();
			parent = parent.Get(column.getParentid());
			column.setParentlist(parent.getParentlist() + "," + parent.getId());
		} else {
			column.setParentlist("-1");
		}
		column.setType(1);
		column.setFunction(0);
		column.setId(SequenceManager.nextID(Columnz.class.getSimpleName()));
		column.Save();
		return column;
	}
	
	

	public boolean deleteCoumns() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		column = new Columnz();
		column.setId(rc.param("id", -1L));
		if (column.getId() == -1L)
			return false;
		// 要小心，这里会非常的复杂

		// 第一步，取出自己的数据备用
		Columnz _self = column.Get(column.getId());
		String key = _self.getParentlist() + "," + _self.getId();
		String columnidList = _self.getId().toString();
		String filter = "columnid = " + _self.getId();
		// 第二步，取出自己所有子节点ID备用
		if (_self.getChild() > 0) {
			columnidList = column.inIdList(key) + "," + _self.getId();
			filter = "columnid in (" + columnidList + ")";
		}
		// 第三步，取出包括子节点的所有文章ID列表
		Article article = new Article();
		int _step = 500;// 步长，如果数据量过大，按步长来取数据，避免出现内存和响应问题
		int total = article.TotalCount(filter);
		List<List<Long>> lists = new ArrayList<List<Long>>();

		double _count = total / _step;
		if (_count <= 0)
			_count = 1;
		_count = Math.ceil(_count);
		// System.out.println("_count : "+ _count);

		for (int i = 0; i < ((int) _count); i++) {
			// System.out.println("i : "+ i);
			List<Long> tmpList = article.idListFilterByID(filter, i + 1, _step);
			lists.add(tmpList);
		}
		// 第四步，取出所有文章后进行分组，免得数据过长
		List<StringBuilder> stringList = new ArrayList<StringBuilder>();
		StringBuilder string = new StringBuilder("");
		_step = 50;
		for (int i = 0; i < lists.size(); i++) {
			List<Long> tmp = lists.get(i);
			for (int n = 0; n < tmp.size(); n++) {
				if (n > 0 && n % _step != 0)
					string.append(',');
				string.append(tmp.get(n));

				if ((n + 1) % _step == 0) {
					// System.out.println("string : " + string);
					stringList.add(string);
					string = new StringBuilder("");
				}
				if ((i == tmp.size() - 1) && !"".equals(string.toString())) {
					stringList.add(string);
				}
			}
		}
		// 第五步，取出所有文章的图片和附件列表
		List<String> paths = new ArrayList<String>();
		Articlefiles files = new Articlefiles();
		Articlephotos photos = new Articlephotos();
		for (StringBuilder str : stringList) {
			filter = "articleid in (" + str.toString() + ")";

			// 附件的
			total = files.TotalCount(filter);
			//System.out.println(" files total : " + total);
			List<Long> tmpList = null;
			List<?> tmp = null;
			if (total > 0) {
				tmpList = files.idListFilter(filter, 1, total);
				tmp = files.BatchGet(tmpList);
				//System.out.println(" files tmp : " + tmp.size());
				for (Object afile : tmp) {

					Articlefiles filetmp = (Articlefiles) afile;
					paths.add(filetmp.getFileserverpath());
				}
			}
			// 图片的
			total = photos.TotalCount(filter);
			if (total > 0) {
				//System.out.println(" photos total : " + total);
				tmpList = photos.idListFilter(filter, 1, total);
				tmp = photos.BatchGet(tmpList);
				for (Object aphoto : tmp) {
					Articlephotos phototmp = (Articlephotos) aphoto;
					paths.add(phototmp.getFileserverpath());
					paths.add(phototmp.getThumbpath());
				}
			}
		}

		// 第六步， 采用事务删除文章图片、附件、文章、子栏目、栏目数据、更新父节点数据
		String deletePhoto = "DELETE FROM articlephotos WHERE articleid in (?)";
		String deleteFiles = "DELETE FROM articlefiles WHERE articleid in (?)";
		String deleteArticle = "DELETE FROM article WHERE columnid in ("+columnidList+")";
		String deleteChild = "DELETE FROM columnz WHERE parentlist like '"
				+ _self.getParentlist() + ","+_self.getId()+"%'";
		String deleteSelf = "DELETE FROM columnz WHERE id=?";
		String updateParentNum = "UPDATE columnz SET child=child-"
				+ columnidList.split(",").length + " WHERE id="
				+ _self.getParentid();
		boolean flag = true;
		try {
			QueryHelper.setAutoCommit();
			for (StringBuilder str : stringList) {
				QueryHelper.commitUpdate(deletePhoto, str.toString());
				QueryHelper.commitUpdate(deleteFiles, str.toString());
			}
			//System.out.println("columnidList : "+ columnidList);
			QueryHelper.commitUpdate(deleteArticle);
			QueryHelper.commitUpdate(deleteChild);
			QueryHelper.commitUpdate(deleteSelf, _self.getId());
			QueryHelper.commitUpdate(updateParentNum);
			QueryHelper.commit();
		} catch (Exception e) {
			flag = false;
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				logger.error("删栏目时出现异常：{}", e1.getMessage());
				throw new ErrMsgException("删除栏目时出现异常，请联系管理员！" + e1.getMessage());
			}
			logger.error("删除栏目时出现异常：{}", e.getMessage());
			throw new ErrMsgException("删除栏目时出现异常，请联系管理员！" + e.getMessage());
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				logger.error("删除栏目时出现异常：{}", e2.getMessage());
				throw new ErrMsgException("删除栏目时出现异常，请联系管理员！" + e2.getMessage());
			}
		}
		// 第七步， 删除所有相关硬盘上的文件
		if (flag) {
			for (String path : paths) {
				FileUtils.deleteQuietly(new File(RequestContext.root() + path));
			}
		}
		return true;
	}

	public boolean editCoumns() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		column = null;
		column = rc.form(Columnz.class);
		if (column.getId() == -1L)
			return false;
		String error = column.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		return column.Update();
	}
}
